package com.zhan.rkforum.quartz;

import com.zhan.rkforum.bean.DiscussPost;
import com.zhan.rkforum.service.CommentService;
import com.zhan.rkforum.service.DiscussPostService;
import com.zhan.rkforum.service.ElasticSearchService;
import com.zhan.rkforum.service.LikeService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.RedisKeyUtil;
import lombok.SneakyThrows;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@SuppressWarnings("all")
public class PostScoreRefreshJob implements Job, CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(PostScoreRefreshJob.class);

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static Date epoch;

    static {
        try {
            epoch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-06-01 00:00:00");
        } catch (ParseException e) {
            logger.info("论坛纪元初始化失败！{}",e.getMessage());
        }
    }



    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        BoundSetOperations<String, Object> operations = redisTemplate.boundSetOps(postScoreKey);
        if(operations.size() == 0){
            logger.info("[任务取消] 没有需要刷新的贴子");
            return;
        }
        logger.info("[任务开始] 开始刷新贴子分数" + operations.size());

        while (operations.size() > 0){
            this.refresh((Integer) operations.pop());
        }

        logger.info("[任务结束] 刷新贴子分数完成");
    }

    private void refresh(int postId) throws IOException {
        logger.info("[任务正在执行]");
        DiscussPost post = discussPostService.findDiscussPostById(postId);
        if(post == null){
            logger.info("该贴子不存在：{}", postId);
            return;
        }
        //是否加精
        boolean refining = post.getStatus() == 1;
        //评论数量
        int commentCount = post.getCommentCount();
        //点赞数量
        long likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_POST, postId);
        //计算权重
        double w = (refining ? 75 : 0) + commentCount * 10 + likeCount * 2;
        //计算分数
        double score = Math.log10(Math.max(w, 1)) + (post.getCreateTime().getTime() -  epoch.getTime()) / (3600 * 24 * 1000);
        //更新贴子分数
        discussPostService.updatePostScore(postId, score);
        //更新es贴子数据
        post.setScore(score);
        elasticSearchService.saveDiscussPost(post);



    }
}
